package com.cndw.kungfu.model.queue;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cndw.kungfu.domain.Queue;

/**
 * 系统队列接口
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2011-8-25 上午10:01:20
 */
@Service
public class QueueServer {
	@Autowired
	private QueueManager queueManager;
	private static final ConcurrentHashMap<Integer, QueueHandler> queueMap = new ConcurrentHashMap<Integer, QueueHandler>();
	private static final ConcurrentHashMap<Long, List<Queue>> playerQueueIds = new ConcurrentHashMap<Long, List<Queue>>();

	public synchronized void initQueueMapOnServerStart() {
		List<Queue> dbQueues = queueManager.select();
		for (Queue queue : dbQueues) {
			submitQueue(queue);

		}
	}

	public List<Queue> getQueueIds(long playerId, boolean create) {
		if (playerQueueIds.containsKey(playerId)) {
			return playerQueueIds.get(playerId);
		} else if (create) {
			List<Queue> queues = new ArrayList<Queue>();
			playerQueueIds.putIfAbsent(playerId, queues);
			return playerQueueIds.get(playerId);
		}
		return null;
	}

	public Queue insertQueue(Queue queue) {
		queueManager.insert(queue);
		submitQueue(queue);
		return queue;
	}

	public void updateQueue(Queue queue) {
		queueManager.update(queue);
	}

	public void deleteQueue(Queue queue) {
		queueManager.delete(queue.getId());
		/**
		 * 从列表里面清除
		 */
		getQueueIds(queue.getPlayerId(), true).remove(queue);
	}

	/**
	 * 立即完成任务
	 * 
	 * @param queue
	 */
	public void immediately(Queue queue) {
		if (queue.getQueueHandler() != null) {
			queue.getQueueHandler().run();
		}
		// deleteQueue(queue);

	}

	/**
	 * 把任务提交到系统执行队列中
	 * 
	 * @param queue
	 */
	private void submitQueue(Queue queue) {
		if (queue.getId() == 0) {
			return;
		}
		// 把队列列表初始化给玩家
		getQueueIds(queue.getPlayerId(), true).add(queue);

		// 启动队列事件
		QueueHandler queueHandler = new QueueHandler(queue);
		queueMap.put(queue.getId(), queueHandler);

	}
}
